package com.cwx.mychat.exception;

import com.cwx.mychat.entity.enums.ExceptionBizCodeEnum;
import com.cwx.mychat.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * 捕获controller中的全局异常
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.cwx.mychat.controller"})
public class ExceptionControllerAdvice {

    /**
     * 用于处理数据校验的异常
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题：{}，异常类型：{}", e.getMessage(), e.getClass(), e);
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        //获取校验错误结果
        bindingResult.getFieldErrors().forEach(item -> {
            //获取错误提示
            String defaultMessage = item.getDefaultMessage();
            //获取错误属性的名字
            String field = item.getField();
            map.put(field, defaultMessage);
        });
        return R.error(ExceptionBizCodeEnum.VALID_EXCEPTION.getCode(), ExceptionBizCodeEnum.VALID_EXCEPTION.getMsg());
    }

    /**
     * 用于处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){
        log.error("请求出现问题：{}，异常类型：{}", e.getMessage(), e.getClass(), e);
        if(e instanceof NoHandlerFoundException){
           return R.error();
        } else if (e instanceof BusinessException) {
            //业务错误
            BusinessException businessException = (BusinessException)e;
            return R.error(businessException.getCode(), businessException.getMessage());
        }else{
            return R.error(ExceptionBizCodeEnum.UNKNOWN_EXCEPTION.getCode(),ExceptionBizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
        }
    }
}
